// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from './btnPermission'
import ElementUI from 'element-ui'

import 'element-ui/lib/theme-chalk/index.css'
import './assets/iconfont/iconfont.css'
import 'font-awesome/css/font-awesome.css'

import App from './App.vue'
import router from './router'
import store from './vuex'
import i18n from './i18n/i18n'

import axios from 'axios'

import htmlToPdf from '../src/components/utils/htmlToPdf'

// 允许跨域携带session
axios.defaults.withCredentials=true;

Vue.prototype.axios = axios
Vue.prototype.server = "http://127.0.0.1:5000"
Vue.config.productionTip = false
Vue.prototype.store = store
Vue.use(ElementUI)

import VueCropper from 'vue-cropper'
Vue.use(VueCropper)

Vue.use(htmlToPdf)

//  获取角色信息，根据用户权限动态加载路由
router.beforeEach((to, from, next) => {
  // console.log(store.getters.token)
  // debugger

  if (store.getters.token) {
	axios.get(Vue.prototype.server + "/account/eq_token" + "?token=" + store.getters.token).then(
		res => {
			if(res.data == "1") {
				// console.log(to.path)
				// 此处应该发送axios来验证token是否正确
				store.dispatch('setToken', store.getters.token)
				if (to.path === '/login') {
				  next({path: '/'})
				} else {
				  if (!store.getters.info.role) {
				    // const role = ['/markdown', '/erji', '/erji2', '/siji', '/wuji']
				    !async function getAddRouters () {
				      // 省略 axios 请求代码 通过 token 向后台请求用户权限等信息，这里用假数据赋值
				      await store.dispatch('getInfo', {
				        role: 'superAdmin',
				        permissions: '超级管理员'
				      })
				      await store.dispatch('newRoutes', store.getters.info.role)
				      // console.log(store.getters.addRouters)
				      await router.addRoutes(store.getters.addRouters)
				      next({path: '/index'})
				    }()
				  } else {
				    let is404 = to.matched.some(record => {
				      if(record.meta.role){
				        return record.meta.role.indexOf(store.getters.info.role) === -1
				      }
				    })
				    if(is404){
				      next({path: '/404'})
				      return false
				    }
				    next()
				  }
				}
			}else {
				if (to.path === '/login') {
				  next()
				}
				next({path: '/login'})
			}
		}, res => {
			  if (to.path === '/login') {
			    next()
			  }
			  next({path: '/login'})
		}
	)

  } else {
    if (to.path === '/login') {
      next()
    }
    next({path: '/login'})
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  i18n,
  render: h => h(App),
  components: {App},
  template: '<App/>'
})
